home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9261 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  63 lines

  1. Path: news.clark.net!not-for-mail
  2. From: gusty@clark.net (Harlan Messinger)
  3. Newsgroups: comp.lang.c++
  4. Subject: Placement new = reconstruction?
  5. Date: 29 Feb 1996 15:45:41 GMT
  6. Organization: Clark Internet Services, Inc., Ellicott City, MD USA
  7. Message-ID: <4h4hn5$k8c@clarknet.clark.net>
  8. NNTP-Posting-Host: explorer.clark.net
  9. Mime-Version: 1.0
  10. Content-Type: TEXT/PLAIN; charset=ISO-8859-1
  11. Content-Transfer-Encoding: 8bit
  12. X-Newsreader: TIN [UNIX 1.3 950726BETA PL0]
  13.  
  14. Do I understand correctly that placement new allows for reinitialization 
  15. of an object in place, thereby giving two advantages:
  16.  
  17.     -- elimination of time spent repeatedly allocating and 
  18.         deallocating, and
  19.  
  20.     -- elimination of concern over proper destruction?
  21.  
  22. In other words, if I have a class Bar that itself performs no allocation, 
  23. and I need to perform an operation on a series of Bar objects, instead of 
  24. allocating a new Bar object for each iteration, can I do the following? Is 
  25. there any reason I shouldn't?
  26.  
  27. Finally, is "placement delete" (i.e., a direct call to bar_->~Bar())
  28. required before each placement new, or before bar_ goes out of scope, or
  29. is it optional if Bar doesn't dynamically allocate anything and therefore
  30. doesn't need to DEallocate anything? 
  31.  
  32.     class Bar
  33.     {
  34.     public:
  35.         Bar(const char *stringArg = NULL);
  36.         ~Bar() {}
  37.         void doit();
  38.     };
  39.  
  40.     Bar::Bar(const char *stringArg) { /* whatever */ }
  41.     void Bar::doit() { / * whatever */ }
  42.  
  43.     class Foo
  44.     {
  45.     private:
  46.         Bar bar_; // So bar_ will be destroyed automatically 
  47.                 // when Foo is.
  48.     public:
  49.         Foo() {}
  50.         ~Foo() {}
  51.         void run(const char *stringArg = NULL);
  52.     };
  53.  
  54.     void Foo::run(const char *stringArg)
  55.     {
  56.         new &bar_ Bar(stringArg);
  57.             // Instead of deallocating and reallocating,
  58.             // just create the new version of bar_ in place.
  59.         bar_.doit();
  60.         return;
  61.     }
  62.  
  63.